<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.query.name"
        placeholder="计划名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="filter"
      />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="filter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column prop="id" align="center" label="ID" width="95" sortable>
        <template v-slot="{row}">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="计划名称" sortable align="center">
        <template v-slot="{row}">
          {{ row.name }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="运行状态" align="center">
        <template v-slot="{row}">
          {{ getTaskStatusName(row.status) }}
        </template>
      </el-table-column>
      <el-table-column prop="owner" label="负责人" align="center">
        <template v-slot="{row}">
          {{ row.owner }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" width="200" align="center">
        <template v-slot="{row}">
          <span> {{ row.startAt | parseTime('{y}-{m}-{d}') }} </span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="结束时间" width="200">
        <template v-slot="{row}">
          <span> {{ row.endAt | parseTime('{y}-{m}-{d}') }} </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="350px">
        <template v-slot="{row, $index}">
          <el-button icon="el-icon-caret-right" type="success" size="mini" @click="handleRun(row)">执行</el-button>
          <el-button icon="el-icon-plus" type="primary" size="mini" @click="handleAdd(row)">添加</el-button>
          <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button icon="el-icon-delete" type="danger" size="mini" @click="del(row, $index)">删除</el-button>
          <!-- <el-button :disabled="row.status==='1'?true:false" icon="el-icon-tickets" type="button" size="mini" @click="showReport(row)">查看报告</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="listQuery.totalRecords>0"
      :total="listQuery.totalRecords"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="fetchData"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="550px" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="left" label-width="100px">
        <el-form-item label="计划名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="负责人:" prop="owner">
          <el-select
            v-model="form.owner"
            value-key="id"
            clearable
            filterable
            placeholder="请选择负责人"
          >
            <el-option
              v-for="item in ownerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间:" prop="startAt">
          <el-date-picker
            v-model="form.startAt"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="结束时间:" prop="endAt">
          <el-date-picker
            v-model="form.endAt"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?create():update()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { getTaskStatusName } from '@/enum/taskStatus.js'
import { selectUserByProjectId } from '@/api/user'
import { create as add_test_suit, update as update_testsuit } from '@/api/functional_test/test_case_manage/test_suite'
import { list, del } from '@/api/functional_test/test_case_manage/test_suite'

export default {
  components: { Pagination },
  props: {
    caseType: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      list: null,
      ownerOptions: [],
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        totalRecords: 0,
        orders: undefined,
        query: {
          projectId: this.$store.getters.projectId,
          caseType: this.caseType
        }
      },
      form: {
        id: undefined,
        name: '',
        owner: '',
        startAt: '',
        endAt: '',
        projectId: this.$store.getters.projectId
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      rules: {
        name: [
          { required: true, message: '请输入计划名称', trigger: 'change' },
          { max: 50, message: '计划名称 长度不能超过 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    getTaskStatusName,
    fetchData() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data.list
        this.listQuery.totalRecords = response.data.page.totalRecords
        this.listLoading = false
      })
    },
    filter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    },
    del(row, index) {
      this.$confirm('是否删除此记录?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        del(row.id).then(response => {
          this.$message({ message: '删除成功!', type: 'success' })
          this.list.splice(index, 1)
          this.fetchData()
        })
      })
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: '',
        owner: '',
        startAt: '',
        endAt: ''
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.selectUserByProjectId()
    },
    handleAdd(row) {
      this.form = Object.assign({}, row)
      this.$router.push({ path: '/functional_test/edit_testsuite', query: { suitID: row.id, caseType: this.caseType }})
    },
    handleUpdate(row) {
      this.form = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.selectUserByProjectId()
    },
    create() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.startAt = Date.parse(this.form.startAt)
          this.form.endAt = Date.parse(this.form.endAt)
          this.form.projectId = this.$store.getters.projectId
          this.form.caseType = this.caseType
          add_test_suit(this.form).then(response => {
            this.dialogFormVisible = false
            this.$message({ message: '添加成功!', type: 'success' })
            this.fetchData()
          })
        }
      })
    },
    update() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.form)
          tempData.startAt = Date.parse(this.form.startAt)
          tempData.endAt = Date.parse(this.form.endAt)
          update_testsuit(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.form.id)
            this.fetchData()
            this.list.splice(index, 1, this.form)
            this.dialogFormVisible = false
            this.$message({ message: '修改成功!', type: 'success' })
          })
        }
      })
    },
    showReport(row) {
      this.$router.push({
        path: '/functional_test/result_detail',
        query: { resultId: row.id }
      })
    },
    selectUserByProjectId() {
      selectUserByProjectId(this.listQuery.query.projectId).then(response => {
        this.ownerOptions = response.data
      })
    },
    handleRun(row) {
      this.$router.push({ path: '/functional_test/plan/execute', query: { id: row.id }})
    }
  }
}

</script>
